package node.func.param;

import grammar.Lexer;
import grammar.MyError;
import lexical.Key;
import lexical.Word;
import node.Node;
import node.exp.ConstExp;
import symbol.Function;
import symbol.Symbol;
import symbol.SymbolTable;

import java.util.ArrayList;

public class FuncFParam implements Node {
    private final Lexer lexer;
    private final SymbolTable table;
    private final Node father;
    private final Function function;
    private Symbol symbol;
    private ConstExp exp;
    public ArrayList<Node> nodes = new ArrayList<>();

    public FuncFParam(Lexer lexer, SymbolTable table, Node father, Function function) {
        this.lexer = lexer;
        this.table = table;
        this.father = father;
        this.function = function;
        parseFuncFParam();
    }

    public void parseFuncFParam() {
        Word word = lexer.getWord(1);
        nodes.add(lexer.getCurWord()); // int
        nodes.add(lexer.getCurWord()); // ident
        int dim = 0;
        if (lexer.isWordType(0, Key.LBRACK)) {
            dim++;
            nodes.add(lexer.getCurWord()); // [
            if (lexer.isWordType(0, Key.RBRACK)) {
                nodes.add(lexer.getCurWord()); // ]
            } else {
                lexer.addError(new MyError(lexer.getWord(-1).lineNum, 'k'));
            }
            if (lexer.isWordType(0, Key.LBRACK)) {
                dim++;
                nodes.add(lexer.getCurWord()); // [
                exp = new ConstExp(lexer, table, this);
                nodes.add(exp);
                if (lexer.isWordType(0, Key.RBRACK)) {
                    nodes.add(lexer.getCurWord()); // ]
                } else {
                    lexer.addError(new MyError(lexer.getWord(-1).lineNum, 'k'));
                }
            }
        }
        symbol = new Symbol("param", dim, word, table.getSymbolId());
        function.addParameter(symbol);
    }

    @Override
    public Node getFather() {
        return father;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (Node word : nodes) {
            sb.append(word.toString());
        }
        return sb.append("<FuncFParam>\n").toString();
    }

    @Override
    public String genMidCode() {
        symbol.setSize();
        if (symbol.dim == 2) {
            symbol.setLen_2(exp.getValue());
        }
        return "";
    }
}

